<script setup lang="ts">
import { userGetUserListService, userDeleteUserService } from '@/api/user'
import { type DataTableColumns, NAvatar, NButton, NTag, NIcon, NPopconfirm } from 'naive-ui'
import { ref, onMounted, type Ref, reactive } from 'vue'
import { Add, SearchOutline } from '@vicons/ionicons5'
import { DeleteOutlined } from '@vicons/antd'
import { Reset } from '@vicons/carbon'
import UserDrawer from '@/views/User/components/UserDrawer.vue'

type RowData = {
  id: number
  username: string
  password: string
  nickname: string
  email: string
  gender: number
  avatar: string
  desc: string
  isAdmin: boolean
}

const message = useMessage()
const data: Ref<RowData[]> = ref([])
const isLoading: Ref<boolean> = ref(false)
onMounted(async () => {
  isLoading.value = true
  const res = await userGetUserListService()
  data.value = res.data.data
  isLoading.value = false
})

// 表格列
const createColumns = (): DataTableColumns<RowData> => [
  {
    type: 'selection',
    fixed: 'left'
  },
  {
    title: 'ID',
    key: 'id',
    width: 100,
    fixed: 'left'
  },
  {
    title: '用户名',
    key: 'username',
    fixed: 'left'
  },
  {
    title: '密码',
    key: 'password'
  },
  {
    title: '昵称',
    key: 'nickname'
  },
  {
    title: '邮箱',
    width: 200,

    key: 'email'
  },
  {
    title: '性别',
    key: 'gender',
    width: 100
  },
  {
    title: '头像',
    key: 'avatar',
    width: 100,
    render(row: RowData) {
      return h(NAvatar, { src: row.avatar, round: true })
    }
  },
  {
    title: '描述',
    key: 'desc',
    width: 250
  },
  {
    title: '权限',
    key: 'isAdmin',
    width: 100,
    render(row: RowData) {
      return h(
        NTag,
        { type: row.isAdmin ? 'success' : 'info' },
        { default: () => (row.isAdmin ? '管理人员' : '普通用户') }
      )
    }
  },
  {
    title: '操作',
    key: 'actions',
    fixed: 'right',
    render(row: RowData) {
      return h(
        'div',
        {
          style: {
            display: 'flex',
            justifyContent: 'start',
            gap: '8px'
          }
        },
        {
          default: () => [
            h(
              NButton,
              { type: 'info', ghost: true, size: 'small', onClick: () => open(row.id) },
              { default: () => '编辑' }
            ),
            h(
              NPopconfirm,
              { positiveText: '确定', negativeText: '取消', onPositiveClick: () => handleDelete(row) },
              {
                trigger: () => h(NButton, { type: 'error', ghost: true, size: 'small' }, { default: () => '删除' }),
                default: () => '你确定要删除吗？'
              }
            )
          ]
        }
      )
    }
  }
]
// 分页
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 30],
  onChange: (page: number) => {
    paginationReactive.page = page
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
  }
})
// 表格列
const columns = createColumns()
//搜索
type SearchForm = {
  username?: string | null
  nickname?: string | null
  gender?: number | null
  role?: number | null
}
const searchForm: Ref<SearchForm> = ref({
  username: null,
  nickname: null,
  gender: null,
  role: null
})
const genderOptions = [
  { label: '男', value: 0 },
  { label: '女', value: 1 }
]
//后面要转换的，原本应该是true和false，但是这里是0和1
const roleOptions = [
  { label: '普通用户', value: 0 },
  { label: '管理人员', value: 1 }
]
const onSearch = async (e: MouseEvent) => {
  e.preventDefault()
  const res = await userGetUserListService(searchForm.value)
  //刷新页面数据
  paginationReactive.page = 1
  data.value = res.data.data
  console.log(searchForm.value)
}
const onReset = async (e: MouseEvent) => {
  e.preventDefault()
  searchForm.value = {
    username: '',
    nickname: '',
    gender: null,
    role: null
  }

  //刷新页面数据
  paginationReactive.page = 1
  const res = await userGetUserListService()
  data.value = res.data.data
}

// 删除
const handleDelete = async (row: RowData) => {
  await userDeleteUserService([row.id])
  message.success('删除成功')
  paginationReactive.page = 1
  const res = await userGetUserListService()
  data.value = res.data.data
}
// 批量删除
const ids = ref<number[]>([])
const onUpdateCheckedRowKeys = async (keys: number[]) => {
  ids.value = keys
}
const handleBatchGenerationDelete = async () => {
  if (ids.value.length === 0) return message.error('请选择要删除的用户')
  await userDeleteUserService(ids.value)
  message.success('删除成功')
  paginationReactive.page = 1
  const res = await userGetUserListService()
  data.value = res.data.data
}
// 打开抽屉
const drawRef = ref()
//通过row判断是编辑还是新建
const open = (id?: number) => {
  if (id) {
    drawRef.value.open(id)
  } else {
    drawRef.value.open()
  }
}
//处理抽屉数据更新
const handleUpdateDate = async (operate: string) => {
  const res = await userGetUserListService()
  data.value = res.data.data
  if (operate === 'add') {
    paginationReactive.page = 1
  }
}
</script>

<template>
  <div class="flex flex-col gap-4 h-full">
    <NCard class="h-20 justify-center">
      <n-form inline :model="searchForm">
        <n-grid :cols="24" x-gap="24">
          <n-form-item-gi :span="4">
            <n-input placeholder="请输入要筛选的用户名" v-model:value="searchForm.username" />
          </n-form-item-gi>
          <n-form-item-gi :span="4">
            <n-input placeholder="请输入要筛选的昵称" v-model:value="searchForm.nickname" />
          </n-form-item-gi>
          <n-form-item-gi :span="4">
            <n-select :options="genderOptions" size="medium" v-model:value="searchForm.gender" placeholder="请选择性别">
            </n-select>
          </n-form-item-gi>
          <n-form-item-gi :span="4">
            <n-select :options="roleOptions" size="medium" v-model:value="searchForm.role" placeholder="请选择角色">
            </n-select>
          </n-form-item-gi>
          <n-form-item-gi :span="2" :offset="4">
            <n-button type="info" strong secondary size="medium" icon-placement="left" @click="onSearch">
              <template #icon>
                <n-icon>
                  <SearchOutline />
                </n-icon>
              </template>
              搜索
            </n-button>
          </n-form-item-gi>
          <n-form-item-gi :span="2">
            <n-button type="default" strong secondary size="medium" icon-placement="left" @click="onReset">
              <template #icon>
                <n-icon>
                  <Reset />
                </n-icon>
              </template>
              重置
            </n-button>
          </n-form-item-gi>
        </n-grid>
      </n-form>
    </NCard>
    <NCard>
      <div class="flex justify-between">
        <n-h4>用户列表</n-h4>
        <n-space class="flex gap-4">
          <n-button type="primary" size="small" ghost @click="open()">
            <template #icon>
              <n-icon>
                <Add />
              </n-icon>
            </template>
            添加用户
          </n-button>
          <n-popconfirm @positive-click="handleBatchGenerationDelete" positive-text="确定" negative-text="取消">
            <template #trigger>
              <n-button type="error" size="small" ghost>
                <template #icon>
                  <n-icon>
                    <DeleteOutlined />
                  </n-icon>
                </template>
                批量删除
              </n-button>
            </template>
            你确定要删除吗？
          </n-popconfirm>
        </n-space>
      </div>
      <n-data-table
        :columns="columns"
        :data="data"
        :row-key="(row: RowData) => row.id"
        :max-height="300"
        :min-height="300"
        :scroll-x="1500"
        virtual-scroll
        :pagination="paginationReactive"
        size="small"
        :loading="isLoading"
        flex-height
        @update:checked-row-keys="onUpdateCheckedRowKeys"
      >
        row.id ></n-data-table
      >
    </NCard>
  </div>
  <UserDrawer ref="drawRef" @updateData="handleUpdateDate" />
</template>
